package cmd

import (
	"fmt"
	"github.com/dwbmio/ding-cli/pkg"
	"github.com/dwbmio/ding-cli/pkg/static"
	"github.com/spf13/cobra"
	"github.com/wonderivan/logger"
	"io/ioutil"
	"os"
	"path"
)

type InitHandler struct{}

func (handle *InitHandler) Run() error {
	cwd, _ := os.Getwd()
	var tar = path.Join(cwd, static.DingProjConfig)
	var _, err = os.Stat(tar)
	if !os.IsNotExist(err) {
		return pkg.NewDError(100)
	}
	var sp = path.Join(cwd, static.DingProjLuaPath)
	_, err = os.Stat(tar)
	if os.IsNotExist(err) {
		_ = os.MkdirAll(sp, os.ModePerm)
	}
	err = ioutil.WriteFile(tar, []byte(fmt.Sprintf(static.DingProjConfigContent, cwd, "")), os.ModePerm)
	if err != nil {
		return err
	}
	return nil
}

func Init() *cobra.Command {
	var initCmd = &cobra.Command{
		Use:     "init",
		Version: "0.1.0",
		Short:   UsageInit,
		Long:    UsageInit,
		Run: func(cmd *cobra.Command, args []string) {
			var handler = &InitHandler{}
			var err = handler.Run()
			if err != nil {
				logger.Error(err)
				return
			}
			logger.Info("Init suc!")
		},
	}
	return initCmd
}
